package com.marquis.cloud.controller;

import com.marquis.cloud.client.LoginClient;
import com.marquis.cloud.common.JWTUtils;
import com.marquis.cloud.common.Json;
import com.marquis.cloud.entity.AutUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class LoginController {

    @Autowired
    private LoginClient loginClient;

    /**
     * 登录
     * @param request 请求
     * @param userName 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping(value = "login")
    public Json login(HttpServletRequest request, String userName, String password){
        Json json = new Json();
        if(StringUtils.isEmpty(userName)){
            json.setMessage("请输入用户名");
            return json;
        }
        if(StringUtils.isEmpty(password)){
            json.setMessage("请输入密码");
            return json;
        }
        //根据用户名查询用户信息
        AutUser autUser = loginClient.login(userName);
        if(ObjectUtils.isEmpty(autUser)){
            json.setMessage("用户名或密码错误");
            return json;
        }
        //密文
        String md5Pwd = DigestUtils.md5Hex(userName + password);
        if(!md5Pwd.equals(autUser.getPassword())){
            json.setMessage("用户名或密码错误");
            return json;
        }
        //获取token令牌
        /*String token = authClient.getToken(String.valueOf(autUser.getUserId()));*/
        String token = JWTUtils.getToken(String.valueOf(autUser.getUserId()));
        if(!StringUtils.isEmpty(token)){
            json.setSuccess(true);
            json.setMessage("登录成功");
            json.setResult(token);
        }else {
            json.setMessage("token获取失败");
        }
        return json;
    }
}
